<template>
	<section class="app-container calendar-list-container">
		<el-row class="container-box" v-loading="loading">
			<el-col :span="4" class="left-box">
				<section class="container-left">
					<a href="#single">单选题</a>
					<a href="#double">多选题</a>
					<!-- <a href="#score">评分题</a> -->
					<a href="#entry">输入题</a>
				</section>
			</el-col>
			<el-col class="right-box" :span="20">
				<section class="right-header-title">
					<el-form ref="listQuery" :model="listQuery" label-width="90px">
						<el-form-item label="标题" prop="questionnaire_title" :rules="filter_rules({required:true})">
							<el-input placeholder="请输入标题" style="width: 400px;" v-model="listQuery.questionnaire_title">
							</el-input>
						</el-form-item>
						<el-form-item label="简介" prop="questionnaire_desc" :rules="filter_rules({required:true})">
              <el-input type="textarea" :autosize="{ minRows: 4 }" placeholder="请输入简介" style="width: 600px;" v-model="listQuery.questionnaire_desc" />
						</el-form-item>
						<el-form-item label="活动封面" prop="file_path" :rules="filter_rules({type: 'upload'})">
							<!-- <el-upload class="avatar-uploader" action="/api/backstage/fileUpload" name="file_path" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
								<img v-if="listQuery.file_path" :src="listQuery.file_path" class="avatar">
								<i v-else class="el-icon-plus avatar-uploader-icon"></i>
							</el-upload> -->
              <img v-if="listQuery.file_path" :src="listQuery.file_path" class="avatar" @click="sizeSet">
              <i v-else class="el-icon-plus avatar-uploader-icon" @click="sizeSet"></i>
						</el-form-item>
					</el-form>
				</section>
				<section class="right-header">
          <!-- 单选题 -->
					<section id="single" class="section-box" v-for="(single,index) in singles" :key="index+'a'"> 
              <section>
                <single-temp ref="single" :singleobj="single" :inNum="index" :index="index" />
              </section>
              <div class="right-icon2 add-select" v-if="index == singles.length - 1" @click="addTemp('single')">
                <i class="el-icon-circle-plus"></i>
                <p>添加选项</p>
              </div>
              <div class="right-icon1 add-select" v-else @click="editSing(index)">
                <i class="el-icon-remove"></i>
                <p>删除选项</p>
              </div>
					</section>
          <!-- 多选题 -->
					<section id="double" class="section-box" v-for="(double,index) in doubles" :key="index+'b'">
              <section>
                <double-temp ref="double" :doubleobj="double" :inNum="index+100" :index="index" />
              </section>
              <div class="right-icon2 add-select" v-if="index == doubles.length - 1" @click="doubleTemp('double')">
                <i class="el-icon-circle-plus"></i>
                <p>添加选项</p>
              </div>
              <div class="right-icon1 add-select" v-else @click="editDouble(index)">
                <i class="el-icon-remove"></i>
                <p>删除选项</p>
              </div>
					</section>
          <!-- 评分题 (暂时屏蔽)-->   
					<!-- <section id="score" class="section-box" v-for="(score,index) in scores" :key="index+'c'">
              <section>
                <score-temp ref="score" :scoreobj="score" :inNum="index+200" :index="index" />
              </section>
              <div class="right-icon2 add-select" v-if="index == scores.length - 1" @click="scoreTemp('score')">
                <i class="el-icon-circle-plus"></i>
                <p>添加选项</p>
              </div>
              <div class="right-icon1 add-select" v-else @click="editScore(index)">
                <i class="el-icon-remove"></i>
                <p>删除选项</p>
              </div>
					</section> -->
          <!-- 输入题 -->
					<section id="entry" class="section-box" v-for="(entry,index) in entrys" :key="index+'d'">
              <section>
                <entry-temp ref="entry" :entryobj="entry" :inNum="index+300" :index="index" />
              </section>
              <div class="right-icon2 add-select" v-if="index == entrys.length - 1" @click="entryTemp('entry')">
                <i class="el-icon-circle-plus"></i>
                <p>添加选项</p>
              </div>
              <div class="right-icon1 add-select" v-else @click="editEntry(index)">
                <i class="el-icon-remove"></i>
                <p>删除选项</p>
              </div>
					</section>
					<!-- 提交数据 -->
					<div class="sub-box">
						<el-button type="primary" @click="onSubmit">保存</el-button>
					</div>
				</section>
			</el-col>
		</el-row>
    <section>
      <size-temp ref="size" :img.sync="listQuery.file_path" title="图片设置"></size-temp>
    </section>
	</section>
</template>

<script>
import { toSimplifiedChinese } from "@/utils";
import { questionnaire_save, questionnaire_edit, questionnaire_findById } from "@/api/questionnaire";
import { types } from "./question";
import singleTemp from './components/singleTemp'
import doubleTemp from './components/doubleTemp'
// import scoreTemp from './components/scoreTemp'
import entryTemp from './components/entryTemp'
import sizeTemp from '@/components/draggableSize'

export default {
  name: "createQuestionn",
  // components: { singleTemp, doubleTemp, scoreTemp, entryTemp },
  components: { singleTemp, doubleTemp, entryTemp, sizeTemp },
  data() {
    return {
			isShow: { add: false, dept: false, child: false, transfer: false },
			loading:false,
      listQuery: {file_path:""}, //新增数据初始化
      types: types,
      ossPublicUrl: localStorage.getItem("ossPublicUrl"),
      singles: [{ num:1 }],   //存放单选题数据
      doubles: [{ num:1 }],   //存放多选题数据
      // scores: [{ num:1 }],    //存放评分题数据
      entrys: [{ num:1 }]     //存放输入题数据
    };
  },
  methods: {
    sizeSet(){
      this.$refs.size.open()
    },
    addTemp(e){   //添加单选题
      if(e == 'single'){  
        this.singles.push( { num: this.singles + 1 } )
      }
    },
    editSing(e){  //删除单选题
      this.singles.splice(e, 1);
    },
    doubleTemp(e){  //添加多选题
      if(e == 'double'){   
        this.doubles.push( { num: this.doubles + 1 })
      }
    },
    editDouble(e){  //删除多选题
      this.doubles.splice(e, 1);
    },
    // scoreTemp(e){  //添加评分题
    //   if(e == 'score'){   
    //     this.scores.push( { num: this.scores + 1 } )
    //   }
    // },
    // editScore(e){   //删除评分题
    //   this.scores.splice(e, 1);
    // },
    entryTemp(e){   //添加输入题
      if(e == 'entry'){   
        this.entrys.push( { num: this.entrys + 1 } )
      }
    },
    editEntry(e){   //删除输入题
      this.entrys.splice(e, 1);
    },
    beforeAvatarUpload(file) {
      let name = file.name.split(".");
      if ( name[name.length - 1] === "jpg" || name[name.length - 1] === "jpeg" || name[name.length - 1] === "png" ) {
        return file;
      } else {
        this.$message.error("图片只能是 jpeg/png 格式!");
        return false;
      }
    },
    handleAvatarSuccess(res, file) {
      this.listQuery.file_path = this.ossPublicUrl + "/" + res.data.file_path;
    },
    async validates() {  //校验其他数据 
      let flag = false;
      this.$refs["listQuery"].validate(valid => {
        flag = valid;
        if (!valid) {
          return false;
        }
      });
      return flag;
    },
    //提交保存
    async onSubmit() {
      //1校验 单选题
      let singQess = []
      let singList = []
      for (let i = 0; i < this.singles.length; i++) {
        singList[i] = await this.$refs['single'][i].validate();
        singQess[i] = await this.$refs['single'][i].getData();
      }
      //2校验 多选题
      let doubleQess = []
      let doubleList = []
      for (let j = 0; j < this.doubles.length; j++) {
        doubleList[j] = await this.$refs['double'][j].validate();
        doubleQess[j] = await this.$refs['double'][j].getData();
      }
      //3校验 评分题
      // let scoreQess = []
      // let scoreList = []
      // for (let m = 0; m < this.scores.length; m++) {
      //   scoreList[m] = await this.$refs['score'][m].validate();
      //   scoreQess[m] = await this.$refs['score'][m].getData();
      // }
      //4校验 输入题
      let entryQess = []
      let entryList = []
      for (let n = 0; n < this.entrys.length; n++) {
        entryList[n] = await this.$refs['entry'][n].validate();
        entryQess[n] = await this.$refs['entry'][n].getData();
      }
      await this.validates()
      if(singList.includes(false)) return ;
      if(doubleList.includes(false)) return ;
      // if(scoreList.includes(false)) return ;
      if(entryList.includes(false)) return ;

      let listQess=[]
      // listQess.push( ...singQess, ...doubleQess, ...scoreQess, ...entryQess );
      listQess.push( ...singQess, ...doubleQess, ...entryQess );
      this.listQuery.questionnaireQess=JSON.stringify(listQess);
      if (this.$route.query.name == "add") {
        this.saveObj();
      } else {
        this.editObj();
      }
    },
    async saveObj() {    //保存
			this.loading = true;
      let query = { ...this.listQuery, company_id: localStorage.getItem("companyId") - 0}
      let { data } = await questionnaire_save(query);
      this.loading = false;
      if (data.status == 100) {
        this.$message.success("添加成功");
        this.$router.push("/other/question");
      }
    },
    async editObj() {    //修改
			this.loading = true;
      let query = { ...this.listQuery, company_id: localStorage.getItem("companyId") - 0}
      let { data } = await questionnaire_edit(query);
      if (data.status == 100) {
        this.$message.success("修改成功");
        this.$router.push("/other/question");
      }
      this.loading = false;
    },
    async initList() {        //获取数据
      this.singles = [];
      this.doubles = [];
      // this.scores = [];
      this.entrys = [];
      let query = Object.assign({},{ id: this.$route.query.id },{company_id: localStorage.getItem("companyId") - 0});
      let { data } = await questionnaire_findById(query);
      if (data.status == 100) {
        this.listQuery = data.data;
        for (let i = 0; i < data.data.questionnaireQess.length; i++) {
          let element = data.data.questionnaireQess[i];
          if (element.question_type==1) {
            this.singles.push(element)
          }
          if (element.question_type==2) {
            this.doubles.push(element)
          }
          // if (element.question_type==3) {   
          //   this.scores.push(element)
          // }
          if (element.question_type==4) {
            this.entrys.push(element)
          }
        }
        // this.singles.sort((val1,val2) => {
        //     return val1.id - val2.id;
        // });
        // this.doubles.sort((val1,val2) => {
        //     return val1.id - val2.id;
        // });
        // this.scores.sort((val1,val2) => {
        //     return val1.id - val2.id;
        // });
        // this.entrys.sort((val1,val2) => {
        //     return val1.id - val2.id;
        // });
      }
		}
  },
  created() {
    if (this.$route.query.name == "edit") {  //判断是编辑还是新增
      this.initList();
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
$border: 1px dashed #d9d9d9;
$picture-size: 120px;
$color: #606266;
.left-box {
  position: fixed;
  width: 250px;
  background-color: #fff;
}
.container-left {
  height: 100%;
  padding: 20px 40px;
  background-color: #fff;
  margin-right: 10px;
  text-align: center;
  display: flex;
  flex-direction: column;
  a {
    padding: 10px;
    border-bottom: 1px solid #ccc;
    border-left: 1px solid #ccc;
    border-right: 1px solid #ccc;
  }
  a:nth-child(1) {
    border-top: 1px solid #ccc;
  }
}
.right-box {
  margin-left: 260px;
}
.right-header-title {
  background-color: #fff;
  padding: 20px;
  margin-bottom: 10px;
}
.right-header {
  .section-box {
    background-color: #fff;
    padding: 20px;
    margin-bottom: 10px;
  }
}
.right-icon1 {
  color: #f56c6c;
  font-size: 26px;
  text-align: right;
  cursor: pointer;
}
.right-icon2 {
  color: #409eff;
  font-size: 26px;
  text-align: right;
  cursor: pointer;
}
.add-select {
  display: flex;
  justify-content: center;
  align-items: center;
  p {
    padding-left: 10px;
    font-size: 16px;
    cursor: pointer;
  }
}
.sub-box {
  background-color: #fff;
  text-align: center;
  padding: 20px;
}
.avatar-uploader {
  .el-upload {
    border: $border;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    &:hover {
      border-color: #409eff;
    }
  }
}
.avatar-uploader-icon {
  border: $border;
  font-size: 28px;
  color: #8c939d;
  width: $picture-size;
  height: $picture-size;
  line-height: $picture-size;
  text-align: center;
  border-radius: 5px;
  cursor: pointer;
}
.avatar {
  width: 60%;
  display: block;
  border-radius: 5px;
  cursor: pointer;
}
</style>
